import { getThirdWechatSessionId } from "@/apis";
import store from "@/store/index.js";

const wechatLogin = async () => {
  const res = await uni.login();
  if (res && res[1].errMsg === "login:ok") {
    const codeStr = res[1].code;
    const sessionId = await getSessionId(codeStr);
    return sessionId;
  } else {
    throw new Error("Login failed");
  }
};

const getSessionId = async (codeStr) => {
  const res = await getThirdWechatSessionId({
    platform: "miniProgram",
    payload: encodeURIComponent(
      JSON.stringify({
        code: codeStr,
        auto_login: false,
      })
    ),
  });
  const sessionId = res.data.session_id;
  return sessionId;
};

export { wechatLogin };